package com.stn.zjx.givingtreasure.activity.address;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.hhl.library.FlowTagLayout;
import com.hhl.library.OnTagSelectListener;
import com.kyleduo.switchbutton.SwitchButton;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.smarttop.library.bean.City;
import com.smarttop.library.bean.County;
import com.smarttop.library.bean.Province;
import com.smarttop.library.bean.Street;
import com.smarttop.library.db.manager.AddressDictManager;
import com.smarttop.library.utils.LogUtil;
import com.smarttop.library.widget.AddressSelector;
import com.smarttop.library.widget.BottomDialog;
import com.smarttop.library.widget.OnAddressSelectedListener;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.adapter.TagAdapter;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.domain.StatusDomain;
import com.stn.zjx.givingtreasure.event.AddressEvent;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.UserAddressNetImpl;
import com.stn.zjx.givingtreasure.service.AmapLocationService;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.vondear.rxtools.RxRegTool;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddAddressActivity extends BaseActivity implements OnAddressSelectedListener, AddressSelector.OnDialogCloseListener, AddressSelector.onSelectorAreaPositionListener, AMapLocationListener {


    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.share_bt)
    RelativeLayout shareBt;
    @BindView(R.id.select_address)
    RelativeLayout selectAddress;
    @BindView(R.id.size_flow_layout)
    FlowTagLayout sizeFlowLayout;
    @BindView(R.id.name_edit)
    EditText nameEdit;
    @BindView(R.id.phone_edit)
    EditText phoneEdit;
    @BindView(R.id.province_city_area)
    TextView provinceCityArea;
    @BindView(R.id.is_default_sb)
    SwitchButton isDefaultSb;
    @BindView(R.id.address_edit)
    EditText addressEdit;
    private TagAdapter mSizeTagAdapter;

    private String provinceCode;
    private String cityCode;
    private String countyCode;
    private String streetCode;
    private int provincePosition=0;
    private int cityPosition=0;
    private int countyPosition=0;
    private int streetPosition=0;
    private AddressDictManager addressDictManager;
    private BottomDialog dialog;
    String userAddressProvinceCityArea = "";
    JSONObject userAddressExtra = new JSONObject();
    private String tag="家";
    AmapLocationService amapLocationService=null;
    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    public void initComponent() {
        actionTitle.setText(getString(R.string.add_address));
        sureBt.setVisibility(View.VISIBLE);
        mSizeTagAdapter = new TagAdapter(this);
        sizeFlowLayout.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_SINGLE);
        sizeFlowLayout.setAdapter(mSizeTagAdapter);
        sizeFlowLayout.setOnTagSelectListener(new OnTagSelectListener() {
            @Override
            public void onItemSelect(FlowTagLayout parent, List<Integer> selectedList) {
                if (selectedList.size() == 0) {
                    return;
                }
                tag=mSizeTagAdapter.mDataList.get(selectedList.get(0));
            }
        });
        List<String> da = new ArrayList<>();
        da.add("家");
        da.add("公司");
        da.add("学校");
        mSizeTagAdapter.onlyAddAll(da);
        //  sizeFlowLayout.clearAllOption();


        initSelector();
    }

    public void initSelector() {
        AddressSelector selector = new AddressSelector(this);
        //获取地址管理数据库
        addressDictManager = selector.getAddressDictManager();
        selector.setTextSize(14);//设置字体的大小
        selector.setIndicatorBackgroundColor(R.color.colorAccent);//设置指示器的颜色
        //        selector.setBackgroundColor(android.R.color.holo_red_light);//设置字体的背景

        selector.setTextSelectedColor(R.color.colorAccent);//设置字体获得焦点的颜色
        selector.setTextSelectedColor(R.color.default_black);//设置字体获得焦点的颜色

        //AddressDictManager addressDictManager = selector.getAddressDictManager();
//        AdressBean.ChangeRecordsBean changeRecordsBean = new AdressBean.ChangeRecordsBean();
//        changeRecordsBean.parentId = 0;
//        changeRecordsBean.name = "测试省";
//        changeRecordsBean.id = 35;
//        addressDictManager.inserddress(changeRecordsBean);//对数据库里增加一个数据
//        selector.setOnAddressSelectedListener(new OnAddressSelectedListener() {
//            @Override
//            public void onAddressSelected(Province province, City city, County county, Street street) {
//
//            }
//        });

        dialog = new BottomDialog(this);
        dialog.setOnAddressSelectedListener(this);
        dialog.setDialogDismisListener(this);
        dialog.setTextSize(14);//设置字体的大小
        dialog.setIndicatorBackgroundColor(R.color.colorAccent);//设置指示器的颜色
        dialog.setTextSelectedColor(R.color.colorAccent);//设置字体获得焦点的颜色
        dialog.setTextUnSelectedColor(R.color.default_black);//设置字体没有获得焦点的颜色
     //   dialog.setDisplaySelectorArea("31", 1, "2704", 1, "2711", 0, "15582", 1);//设置已选中的地区
        dialog.setSelectorAreaPositionListener(this);

    }


    public void startLocation(){
        showLoading();
        amapLocationService=new AmapLocationService(this);
        amapLocationService.registerListener(this);
        amapLocationService.start();

    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_address);
        ButterKnife.bind(this);
        initComponent();
    }

    @OnClick({R.id.back_bt, R.id.select_address, R.id.sure_bt,R.id.location_bt})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case  R.id.location_bt:
               startLocation();
                break;
            case R.id.back_bt:
                finish();
                break;
            case R.id.select_address:
                if (dialog != null) {
                    dialog.show();
                }

                break;
            case R.id.sure_bt:
                if (TextUtils.isEmpty(nameEdit.getText().toString().trim())) {
                     showToast(getString(R.string.please_input_realname));
                    return;
                }
                if (TextUtils.isEmpty(phoneEdit.getText().toString().trim())) {
                    showToast(getString(R.string.please_input_contact_iphone));
                    return;
                }

                if (!RxRegTool.isMobile(phoneEdit.getText().toString().trim())) {
                    showToast(getString(R.string.please_isnotreal_phone));
                    return ;
                }

                if (TextUtils.isEmpty(userAddressProvinceCityArea)) {
                    showToast(getString(R.string.please_select_province_city_area));
                    return;
                }
                if (TextUtils.isEmpty(tag)) {
                    showToast(getString(R.string.please_input_address_tag));
                    return;
                }
                if (TextUtils.isEmpty(addressEdit.getText().toString().trim())) {
                    showToast(getString(R.string.please_input_detail_address));
                    return;
                }
                Integer isDefault=0;
                if(isDefaultSb.isChecked()){
                    isDefault=1;
                }else{
                    isDefault=0;
                }
                add(nameEdit.getText().toString().trim(),
                        phoneEdit.getText().toString().trim(),
                        userAddressProvinceCityArea,
                       addressEdit.getText().toString().trim(),
                        tag,
                        userAddressExtra.toString(),
                        isDefault
                );
                break;

        }
    }


    @Override
    public void onAddressSelected(Province province, City city, County county, Street street) {
        provinceCode = (province == null ? "" : province.code);
        cityCode = (city == null ? "" : city.code);
        countyCode = (county == null ? "" : county.code);
        streetCode = (street == null ? "" : street.code);
        LogUtil.d("数据", "省份id=" + provinceCode);
        LogUtil.d("数据", "城市id=" + cityCode);
        LogUtil.d("数据", "乡镇id=" + countyCode);
        LogUtil.d("数据", "街道id=" + streetCode);
        String s = (province == null ? "" : province.name) + (city == null ? "" : city.name) + (county == null ? "" : county.name) +
                (street == null ? "" : street.name);
        provinceCityArea.setTextColor(getResources().getColor(R.color.default_black));
        provinceCityArea.setText(s);
        userAddressProvinceCityArea = s;

        try {
            if (province != null && !province.code.equals("")) {
                userAddressExtra.put("provinceCode", provinceCode);
            }
            if (city != null && !city.code.equals("")) {
                userAddressExtra.put("cityCode", cityCode);
            }
            if (county != null && !county.code.equals("")) {
                userAddressExtra.put("countyCode", countyCode);
            }
            if (street != null && !street.code.equals("")) {
                userAddressExtra.put("streetCode", streetCode);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (dialog != null) {
            dialog.dismiss();
        }
    }

    @Override
    public void dialogclose() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    /**
     * 根据code 来显示选择过的地区
     */
    private void getSelectedArea() {
        String province = addressDictManager.getProvince(provinceCode);
        String city = addressDictManager.getCity(cityCode);
        String county = addressDictManager.getCounty(countyCode);
        String street = addressDictManager.getStreet(streetCode);
        LogUtil.d("数据", "省份=" + province);
        LogUtil.d("数据", "城市=" + city);
        LogUtil.d("数据", "乡镇=" + county);
        LogUtil.d("数据", "街道=" + street);
    }

    @Override
    public void selectorAreaPosition(int provincePosition, int cityPosition, int countyPosition, int streetPosition) {
        this.provincePosition = provincePosition;
        this.cityPosition = cityPosition;
        this.countyPosition = countyPosition;
        this.streetPosition = streetPosition;


        try {
            userAddressExtra.put("provincePosition", provincePosition);
            userAddressExtra.put("cityPosition", cityPosition);
            userAddressExtra.put("countyPosition", countyPosition);
            userAddressExtra.put("streetPosition", streetPosition);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        LogUtil.d("数据", "省份位置=" + provincePosition);
        LogUtil.d("数据", "城市位置=" + cityPosition);
        LogUtil.d("数据", "乡镇位置=" + countyPosition);
        LogUtil.d("数据", "街道位置=" + streetPosition);
    }

    public void add(String userAddressName,
                     String userAddressPhone,
                     String userAddressProvinceCityArea,
                     String userAddressAddress,
                     String userAddressTag,
                     String userAddressExtra,
                     Integer addressIsDefault){
        User userOnline= UserService.getInstance(getApplicationContext())
                .getOnlineLoginUser();
        if(userOnline==null){
            return;
        }
        UserAddressNetImpl
                .add_address(userOnline.getToken(),
                        userAddressName,
                        userAddressPhone,
                        userAddressProvinceCityArea,
                        userAddressAddress,
                        userAddressTag,
                        userAddressExtra,
                        addressIsDefault,
                        "add_address",
                        new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                              showLoading();
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                dissmissLoading();
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                if(response.isSuccessful()){
                                    StatusDomain domain=new Gson().fromJson(response.body(),StatusDomain.class);
                                    switch (domain.getStatus()){
                                        case BaseApi.REQUEST_SUCCESS_CODE:
                                            AddressEvent event=new AddressEvent();
                                            event.flag=1;
                                            EventBus
                                                    .getDefault().post(event);
                                            finish();
                                            break;
                                        default:
                                            showToast(domain.getMessage());
                                            break;
                                    }

                                }

                            }
                        });
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation.getErrorCode() == 0) {
            userAddressProvinceCityArea=aMapLocation.getProvince()+aMapLocation.getCity()+aMapLocation.getDistrict();
            provinceCityArea.setTextColor(getResources().getColor(R.color.default_black));
            provinceCityArea.setText(userAddressProvinceCityArea);
          if(aMapLocation.getAddress().length()<9){
              addressEdit.setText(aMapLocation.getAddress());
          }else {
               addressEdit.setText(aMapLocation.getAddress().substring(9,aMapLocation.getAddress().length()));
          }
        }else{
            showToast(aMapLocation.getErrorInfo());
        }
        dissmissLoading();

    }


}
